<template>
  <div class="page">
    <h2>神经调控 — 刺激方案库与参数管理</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按方案名/靶区/标签搜索" clearable style="flex:1" />
      <el-select v-model="filterModality" placeholder="刺激方式" style="width:160px">
        <el-option label="全部" :value="''" />
        <el-option label="rTMS" value="rTMS" />
        <el-option label="iTBS" value="iTBS" />
        <el-option label="tDCS" value="tDCS" />
        <el-option label="DBS" value="DBS" />
      </el-select>
      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openProtocol()">新建方案</el-button>
        <el-button @click="exportCSV">导出</el-button>
        <el-button @click="() => fileInput.click()">导入</el-button>
      </div>
    </div>

    <div class="muted">提示：可在方案库中保存常用参数模板，支持按指南版本标注来源及禁忌/注意事项。</div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px">
      <el-table-column prop="name" label="方案名称" width="220" />
      <el-table-column prop="modality" label="方式" width="100" />
      <el-table-column prop="target" label="靶区/部位" width="180" />
      <el-table-column prop="paramsSummary" label="参数摘要" />
      <el-table-column prop="tags" label="标签" width="160" />
      <el-table-column prop="version" label="来源/版本" width="140" />
      <el-table-column label="启用" width="80">
        <template #default="{ row }">
          <el-switch v-model="row.enabled" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="{ row }">
          <el-button size="small" @click="openProtocol(row.id)">编辑</el-button>
          <el-button size="small" type="primary" @click="applyProtocol(row.id)" style="margin-left:8px">应用</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="方案编辑" :model-value="showEditor" width="820px" @close="closeEditor">
      <el-form :model="protocolForm" label-width="140px">
        <el-form-item label="方案名称">
          <el-input v-model="protocolForm.name" />
        </el-form-item>
        <el-form-item label="刺激方式">
          <el-select v-model="protocolForm.modality" style="width:220px">
            <el-option label="rTMS" value="rTMS" />
            <el-option label="iTBS" value="iTBS" />
            <el-option label="tDCS" value="tDCS" />
            <el-option label="DBS" value="DBS" />
          </el-select>
        </el-form-item>
        <el-form-item label="靶区/部位">
          <el-input v-model="protocolForm.target" placeholder="例如：左DLPFC (F3) 或经影像定位" />
        </el-form-item>
        <el-form-item label="主要参数摘要">
          <el-input v-model="protocolForm.paramsSummary" />
        </el-form-item>
        <el-form-item label="详细参数">
          <el-input type="textarea" v-model="protocolForm.details" placeholder="如：频率、强度、脉冲数、脉冲宽度等" />
        </el-form-item>
        <el-form-item label="强度/浓度">
          <el-input v-model="protocolForm.intensity" placeholder="如：80% RMT / 1.5 mA" style="width:240px" />
        </el-form-item>
        <el-form-item label="频率/模式">
          <el-input v-model="protocolForm.frequency" placeholder="如：10 Hz / iTBS" style="width:240px" />
        </el-form-item>
        <el-form-item label="每次脉冲/时长">
          <el-input v-model="protocolForm.pulses" placeholder="例如：600 脉冲" style="width:240px" />
        </el-form-item>
        <el-form-item label="每周/总疗程">
          <el-input v-model="protocolForm.sessionsPerWeek" placeholder="每周次数" style="width:120px;margin-right:8px" />
          <el-input v-model="protocolForm.totalSessions" placeholder="总次数" style="width:120px" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="protocolForm.tags" multiple style="width:420px">
            <el-option v-for="t in tagOptions" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="来源/指南版本">
          <el-input v-model="protocolForm.version" placeholder="例如：CNS 2023 指南" />
        </el-form-item>
        <el-form-item label="备注/注意事项">
          <el-input type="textarea" v-model="protocolForm.notes" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditor">取消</el-button>
        <el-button type="primary" @click="saveProtocol">保存</el-button>
      </template>
    </el-dialog>

    <input ref="fileInput" type="file" accept=".csv" style="display:none" @change="handleFile" />
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT = [
  { id:1, name:'抑郁 rTMS 高频 10Hz', modality:'rTMS', target:'左DLPFC', paramsSummary:'10Hz 3000 pulses/次 80% RMT', details:'频率:10Hz;强度:80%RMT;脉冲:3000', intensity:'80% RMT', frequency:'10 Hz', pulses:'3000', sessionsPerWeek:'5', totalSessions:'20', tags:['抗抑郁'], version:'指南 v1', notes:'注意癫痫史', enabled:true },
  { id:2, name:'抗抑郁 iTBS 快速方案', modality:'iTBS', target:'左DLPFC', paramsSummary:'iTBS 600 pulses/次 80% RMT', details:'iTBS 模式，600 脉冲', intensity:'80% RMT', frequency:'iTBS', pulses:'600', sessionsPerWeek:'5', totalSessions:'30', tags:['抗抑郁','快速'], version:'研究方案', notes:'短时窗疗效数据', enabled:true }
];

const data = ref(JSON.parse(JSON.stringify(DEFAULT)));
const q = ref('');
const filterModality = ref('');

const showEditor = ref(false);
const editingId = ref(null);
const protocolForm = reactive({ name:'', modality:'rTMS', target:'', paramsSummary:'', details:'', intensity:'', frequency:'', pulses:'', sessionsPerWeek:'', totalSessions:'', tags:[], version:'', notes:'', enabled:true });
const tagOptions = ['抗抑郁','强迫症','慢性疼痛','快速方案','儿童慎用'];

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !( (d.name||'').toLowerCase().includes(qq) || (d.target||'').toLowerCase().includes(qq) || (d.tags||[]).join(',').toLowerCase().includes(qq) )) return false;
    if(filterModality.value && d.modality !== filterModality.value) return false;
    return true;
  });
});

function openProtocol(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(protocolForm, JSON.parse(JSON.stringify(it))); } else { Object.assign(protocolForm,{name:'',modality:'rTMS',target:'',paramsSummary:'',details:'',intensity:'',frequency:'',pulses:'',sessionsPerWeek:'',totalSessions:'',tags:[],version:'',notes:'',enabled:true}); } showEditor.value = true; }
function closeEditor(){ showEditor.value = false; editingId.value = null; }
function saveProtocol(){ if(!protocolForm.name){ ElMessage.warning('方案名称为必填'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(protocolForm))); } else { const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({id:nid}, JSON.parse(JSON.stringify(protocolForm)))); }
  showEditor.value=false; ElMessage.success('已保存方案'); }

function deleteOne(id){ ElMessageBox.confirm('确认删除该方案？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}

function applyProtocol(id){ const it = data.value.find(x=>x.id===id); if(!it){ ElMessage.warning('找不到方案'); return; } // 应用到当前患者—此处为示例
  ElMessage.success(`已将方案 "${it.name}" 设为当前应用方案（示例）`);
}

function exportCSV(){ const csv = [ ['id','name','modality','target','paramsSummary','intensity','frequency','pulses','sessionsPerWeek','totalSessions','tags','version','notes','enabled'], ...data.value.map(d=>[d.id,d.name,d.modality,d.target,d.paramsSummary,d.intensity,d.frequency,d.pulses,d.sessionsPerWeek,d.totalSessions,(d.tags||[]).join('|'),d.version,d.notes,d.enabled]) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='protocols.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function handleFile(e){ const f = e.target.files[0]; if(!f) return; const reader = new FileReader(); reader.onload = function(ev){ try{ const text = ev.target.result; const rows = text.split(/\r?\n/).map(r=>r.trim()).filter(Boolean); if(rows.length<2){ ElMessage.warning('没有有效数据'); return; } const headers = parseCSVLine(rows[0]); const items = rows.slice(1).map(r=>parseCSVLine(r)).map(cols=>{ const obj={}; headers.forEach((h,i)=>obj[h.trim()]=cols[i]||''); return obj; }); items.forEach(it=>{ const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push({ id:nid, name:it.name||'未命名', modality:it.modality||'rTMS', target:it.target||'', paramsSummary:it.paramsSummary||'', intensity:it.intensity||'', frequency:it.frequency||'', pulses:it.pulses||'', sessionsPerWeek:it.sessionsPerWeek||'', totalSessions:it.totalSessions||'', tags:(it.tags?it.tags.split('|'):[ ]), version:it.version||'', notes:it.notes||'', enabled: (it.enabled==='true' || it.enabled===true) }); }); ElMessage.success('导入完成'); }catch(err){ ElMessage.error('导入失败'); }}; reader.readAsText(f,'utf-8'); e.target.value=''; }

function parseCSVLine(line){ const cols=[]; let cur=''; let inQ=false; for(let i=0;i<line.length;i++){ const ch=line[i]; if(inQ){ if(ch==='"'){ if(line[i+1]==='"'){ cur+='"'; i++; }else{ inQ=false; } }else{ cur+=ch; } }else{ if(ch==='"'){ inQ=true; }else if(ch===','){ cols.push(cur); cur=''; }else{ cur+=ch; } } } cols.push(cur); return cols; }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>
